package com.jh.user.business.impl;

import cn.jh.common.exception.ServiceException;
import com.jh.user.business.ChanPayBankBusiness;
import com.jh.user.pojo.ChanPayBank;
import com.jh.user.pojo.enums.ChanBank;
import com.jh.user.pojo.enums.ChanPay;
import com.jh.user.repository.ChanPayBankRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ChanPayBankBusinessImpl implements ChanPayBankBusiness {
    private static final Logger log = LoggerFactory.getLogger(ChanPayBankBusinessImpl.class);

    private final ChanPayBankRepository chanPayBankRepository;

    @Autowired
    public ChanPayBankBusinessImpl(ChanPayBankRepository chanPayBankRepository) {
        this.chanPayBankRepository = chanPayBankRepository;
    }

    @Override
    public List<Map<String, Object>> getChanPayBankList() throws ServiceException {
        List<ChanPayBank> head = new ArrayList<>();
        List<ChanPayBank> body = new ArrayList<>();
        List<Map<String, Object>> list = new ArrayList<>();

        List<ChanPayBank> all = chanPayBankRepository.findAll();
        if (null == all || all.size() == 0) {
            throw new ServiceException("未查询到畅捷通道支持的银行卡列表！");
        }

        for (ChanPayBank payBank : all) {
            if (null != payBank) {
                long pid = payBank.getPid();
                if (pid == 0) {
                    head.add(payBank);
                }
                if (pid != 0) {
                    body.add(payBank);
                }
            }
        }

        for (ChanPayBank headBank : head) {
            if (null == headBank) {
                continue;
            }

            List<String> bankName = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            map.put("channelName", ChanBank.of(headBank.getChannelNo()).getDesc());

            long id = headBank.getId();
            for (ChanPayBank bodyBank : body) {
                if (null == bodyBank) {
                    continue;
                }
                long pid = bodyBank.getPid();
                if (id == pid) {
                    bankName.add(bodyBank.getBankName());
                }
            }
            if (bankName.size() > 0) {
                map.put("bankName", bankName);
                list.add(map);
            }
        }

        return list;
    }
}
